package cn.kgc.user.controller;

import cn.kgc.common.entity.Author;
import cn.kgc.user.service.AuthorService;
import cn.kgc.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * Created by teacher ZHANG on 2022/12/5
 */
@Controller
public class LoginController {
    @Autowired
    private AuthorService authorService;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //@CookieValue:取cookie中的值，required:是否必须有
    @RequestMapping("/")
    public String index(@CookieValue(value = "token", required = false) String token, Integer articleId, Model model) {
        if (token != null && userService.findAuthor(token) != null) {
            return "redirect:http://localhost:8088/"; //跳转
        }
        else {
            if (articleId != null) {
                model.addAttribute("articleId", articleId);
            }

            return "login";  //到登录页面
        }
    }

    @RequestMapping("/phone")
    public String phone(@CookieValue(value = "token", required = false) String token, Integer articleId, Model model) {
        if (token != null && userService.findAuthor(token) != null) {
            return "redirect:http://www.news.com.cn:8088/"; //跳转
        }
        else {
            if (articleId != null) {
                model.addAttribute("articleId", articleId);
            }

            return "phone";  //到登录页面
        }
    }

    @RequestMapping("/login")
    public String login(String username, String password, Integer articleId, HttpServletResponse response, Model model) {
        Author author = authorService.findAuthor(username);
        if (author == null) {
            model.addAttribute("error", "用户名不存在");
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            return "login";
        }
        else if (!author.getPassword().equals(password)) {
            model.addAttribute("error", "密码输入错误");
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            return "login";
        }
        else {
            //将用户信息保存至redis
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            userService.saveAuthor(token, author);

            //生成cookie
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");  //绑定域名
            //cookie.setMaxAge(1800);  //若不设置存活时间，则在浏览器关闭后消失

            response.addCookie(cookie); //加入到response中返回给客户端

            String target = "http://localhost:8088/";

            if (articleId != null) {
                target += "article/get_detail?articleId=" + articleId;
            }


            return "redirect:" + target;
        }
    }

    //向手机发送验证码
    @RequestMapping("send_code")
    @ResponseBody
    public Map<String, Object> sendCode(String phone) {
        Map<String, Object> result = new HashMap<>();

        //判断手机号是否有误
        if (!phone.matches("^1[0-9]{10}")) {
            result.put("success", false);
            result.put("message", "手机号码有误");
            return result;
        }

        //查看数据库中是否有此号
        Author author = authorService.findAuthor(phone);
        if (author == null) {
            result.put("success", false);
            result.put("message", "手机号不存在");
            return result;
        }

        //生成四位随机数
        Random random = new Random();
        Integer num = random.nextInt(10000);

        String code = String.format("%04d", num);

        //保存到redis中，时长为60秒
        userService.savePhone(phone, code);

        //发送至手机
        /*
        System.out.println("向手机：" + phone + "发送验证码。");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("验证码发送完毕。");
        */
        //将手机号和验证码放入消息队列中
        redisTemplate.convertAndSend("phone_code", phone + ":" + code);

        //返回
        result.put("success", true);

        return result;
    }

    @RequestMapping("/phone_login")
    @ResponseBody
    public Map<String, Object> phoneLogin(String phone, String code, Integer articleId, HttpServletResponse response, Model model) {
        Map<String, Object> result = new HashMap<>();

        //查看数据库中是否有此号
        Author author = authorService.findAuthor(phone);
        if (author == null) {
            result.put("success", false);
            result.put("message", "手机号不存在");
            return result;
        }

        //从redis中取出验证码
        String value = userService.getPhone(phone);
        if (value == null || !value.equals(code)) {
            result.put("success", false);
            result.put("message", "验证码输入错误");
            return result;
        }

        //将用户信息保存至redis
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        userService.saveAuthor(token, author);

        //生成cookie
        Cookie cookie = new Cookie("token", token);
        cookie.setDomain("news.com.cn");  //绑定域名
        //cookie.setMaxAge(1800);  //若不设置存活时间，则在浏览器关闭后消失

        response.addCookie(cookie); //加入到response中返回给客户端

        String target = "http://www.news.com.cn:8088/";

        if (articleId != null) {
            target += "article/get_detail?articleId=" + articleId;
        }

        result.put("success", true);
        result.put("message", target);

        return result;
    }
}
